<template>
  <div class="todo-container" @mousemove="handleMouseMove">
    <div 
      v-for="(emoji, index) in activeEmojis" 
      :key="index"
      class="follow-emoji"
      :style="emoji.style"
    >
      {{ emoji.icon }}
    </div>

    <el-card class="todo-card">
      <div slot="header">
        <h2>待办清单</h2>
        <el-input
          v-model="newTodo"
          placeholder="添加新的待办事项..."
          class="input-with-select"
          @keyup.enter.native="addTodo"
        >
          <el-button slot="append" type="primary" @click="addTodo">
            <i class="el-icon-plus"></i> 添加
          </el-button>
        </el-input>
      </div>

      <el-row class="statistics-row" type="flex" justify="space-around">
        <el-col :span="7">
          <el-statistic title="全部任务" :value="todos.length">
            <template slot="suffix">
              <i class="el-icon-notebook-1"></i>
            </template>
          </el-statistic>
        </el-col>
        <el-col :span="7">
          <el-statistic title="已完成" :value="completedCount">
            <template slot="suffix">
              <i class="el-icon-check"></i>
            </template>
          </el-statistic>
        </el-col>
        <el-col :span="7">
          <el-statistic title="待完成" :value="pendingCount">
            <template slot="suffix">
              <i class="el-icon-time"></i>
            </template>
          </el-statistic>
        </el-col>
      </el-row>

      <div v-if="todos.length > 0" class="todo-list">
        <div v-for="todo in todos" :key="todo.id" class="todo-item" @click="toggleTodo(todo)">
          <el-row type="flex" align="middle" :gutter="20">
            <el-col :span="2">
              <el-checkbox 
                v-model="todo.completed" 
                @change.stop="toggleTodo(todo)"
              ></el-checkbox>
            </el-col>
            
            <el-col :span="16">
              <template v-if="todo.isEditing">
                <el-input
                  v-model="todo.editTitle"
                  size="small"
                  @keyup.enter.native="saveEdit(todo)"
                  @keyup.esc.native="cancelEdit(todo)"
                  @click.stop
                  ref="editInput"
                  v-focus
                ></el-input>
              </template>
              <span v-else :class="{ 'completed-text': todo.completed }">{{ todo.title }}</span>
            </el-col>
            
            <el-col :span="6" class="todo-actions">
              <template v-if="todo.isEditing">
                <el-button-group>
                  <el-button
                    type="success"
                    size="small"
                    icon="el-icon-check"
                    circle
                    @click.stop="saveEdit(todo)"
                  ></el-button>
                  <el-button
                    type="info"
                    size="small"
                    icon="el-icon-close"
                    circle
                    @click.stop="cancelEdit(todo)"
                  ></el-button>
                </el-button-group>
              </template>
              <template v-else>
                <div class="action-buttons">
                  <el-button
                    type="primary"
                    size="small"
                    icon="el-icon-edit"
                    circle
                    @click.stop="enableEdit(todo)"
                  ></el-button>
                  <el-button
                    type="danger"
                    size="small"
                    icon="el-icon-delete"
                    circle
                    @click.stop="confirmDelete(todo.id)"
                  ></el-button>
                </div>
              </template>
            </el-col>
          </el-row>
        </div>
      </div>

      <el-empty
        v-else
        description="还没有待办事项，快来添加吧！"
      >
        <el-button type="primary" @click="focusInput">
          立即添加
        </el-button>
      </el-empty>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'TodoList',
  data() {
    return {
      todos: [],
      newTodo: '',
      baseURL: 'http://localhost:8080/api/todos',
      emojis: ['🌈', '✨', '🎨', '🎯', '🎪', '🎭', '🎪', '🎡', '🎢', '🎠'],
      activeEmojis: [],
      emojiList: [
        '✨', '🌸', '💖', '🎀', '🌟', '🍭', '🌈', '🦄', '🎨', '🌺', 
        '🎪', '🎭', '🌹', '🌻', '🌼', '🌷', '🍓', '🍰', '🧁', '🍪',
        '🍬', '🎈', '🎉', '🎊', '💫', '💝', '💕', '💞', '💗', '💓',
        '💘', '💌', '🦋', '🌺', '🎵', '🎶', '💎', '✨', '⭐', '🌙',
        '🌈', '🍡', '🍥', '🎠', '🎡', '🎪', '🎭', '🎨', '🎯', '🎲',
        '🎮', '🎸', '🎹', '🎧', '📱', '💻', '🌸', '🍙', '🍜', '🍩'
      ],
      lastEmojiTime: 0
    }
  },
  computed: {
    completedCount() {
      return this.todos.filter(todo => todo.completed).length
    },
    pendingCount() {
      return this.todos.filter(todo => !todo.completed).length
    }
  },
  methods: {
    async fetchTodos() {
      try {
        const response = await axios.get(this.baseURL)
        if (response.data.code === 200) {
          this.todos = response.data.data.map(todo => ({
            ...todo,
            isEditing: false,
            editTitle: todo.title
          }))
        } else {
          this.$message.error(response.data.message || '获取数据失败')
        }
      } catch (error) {
        console.error('获取待办事项失败:', error)
        this.$message.error('获取数据失败')
      }
    },

    async addTodo() {
      const title = this.newTodo.trim()
      if (!title) return

      try {
        const response = await axios.post(this.baseURL, {
          title,
          completed: false
        })
        if (response.data.code === 200) {
          this.newTodo = ''
          this.$message.success(response.data.message)
          await this.fetchTodos()
        } else {
          this.$message.error(response.data.message || '添加失败')
        }
      } catch (error) {
        console.error('添加待办事项失败:', error)
        this.$message.error('添加失败')
      }
    },

    enableEdit(todo) {
      // 先将其他所有项的编辑状态设为false
      this.todos.forEach(t => {
        t.isEditing = false
        t.editTitle = t.title
      })
      
      // 设置当前项的编辑状态
      todo.isEditing = true
      todo.editTitle = todo.title
      
      // 确保输入框获得焦点
      this.$nextTick(() => {
        const inputs = this.$refs.editInput
        if (inputs) {
          const input = Array.isArray(inputs) ? inputs[this.todos.indexOf(todo)] : inputs
          if (input) {
            input.focus()
          }
        }
      })
    },

    async saveEdit(todo) {
      const title = todo.editTitle.trim()
      if (!title) {
        this.cancelEdit(todo)
        return
      }

      try {
        const response = await axios.put(`${this.baseURL}/${todo.id}`, {
          title,
          completed: todo.completed
        })
        if (response.data.code === 200) {
          todo.isEditing = false
          this.$message.success(response.data.message)
          await this.fetchTodos()
        } else {
          this.$message.error(response.data.message || '更新失败')
          this.cancelEdit(todo)
        }
      } catch (error) {
        console.error('更新待办事项失败:', error)
        this.$message.error('更新失败')
        this.cancelEdit(todo)
      }
    },

    cancelEdit(todo) {
      todo.isEditing = false
      todo.editTitle = todo.title
    },

    async deleteTodo(id) {
      try {
        const response = await axios.delete(`${this.baseURL}/${id}`)
        if (response.data.code === 200) {
          this.$message.success(response.data.message)
          await this.fetchTodos()
        } else {
          this.$message.error(response.data.message || '删除失败')
        }
      } catch (error) {
        console.error('删除待办事项失败:', error)
        this.$message.error('删除失败')
      }
    },

    async toggleTodo(todo) {
      try {
        const response = await axios.put(`${this.baseURL}/${todo.id}`, {
          title: todo.title,
          completed: !todo.completed
        })
        if (response.data.code === 200) {
          await this.fetchTodos()
        } else {
          this.$message.error(response.data.message || '更新状态失败')
        }
      } catch (error) {
        console.error('更新待办事项状态失败:', error)
        this.$message.error('更新状态失败')
      }
    },

    handleMouseMove(e) {
      const now = Date.now()
      // 降低生成频率，每200ms生成一个
      if (now - this.lastEmojiTime > 200) {
        this.lastEmojiTime = now
        
        // 创建新的表情
        const emoji = {
          icon: this.emojiList[Math.floor(Math.random() * this.emojiList.length)],
          style: {
            position: 'fixed',
            left: `${e.clientX}px`,
            top: `${e.clientY}px`,
            fontSize: `${Math.random() * 10 + 20}px`,
            pointerEvents: 'none',
            zIndex: 9999,
            opacity: 0.8,
            transform: `translate(-50%, -50%)`
          }
        }
        
        // 添加到活动表情列表
        this.activeEmojis.push(emoji)
        
        // 1.5秒后移除表情
        setTimeout(() => {
          const index = this.activeEmojis.indexOf(emoji)
          if (index > -1) {
            this.activeEmojis.splice(index, 1)
          }
        }, 1500)
      }
    },

    confirmDelete(id) {
      this.$confirm('确定要删除这个待办事项吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteTodo(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    focusInput() {
      this.$nextTick(() => {
        const inputEl = this.$el.querySelector('.todo-input input')
        if (inputEl) inputEl.focus()
      })
    },

    tableRowClassName({row}) {
      if (row.completed) {
        return 'success-row';
      }
      return '';
    }
  },
  mounted() {
    this.fetchTodos()
    // 确保事件监听器被正确添加
    document.addEventListener('mousemove', this.handleMouseMove)
  },
  beforeDestroy() {
    // 组件销毁前移除事件监听器
    document.removeEventListener('mousemove', this.handleMouseMove)
  },
  directives: {
    focus: {
      inserted(el) {
        el.querySelector('input').focus()
      }
    }
  }
}
</script>

<style>
.todo-container {
  max-width: 1400px;
  width: 90%;
  margin: 20px auto;
  padding: 0 20px;
}

.todo-card {
  margin-bottom: 20px;
  background: rgba(255, 255, 255, 0.9) !important;
  backdrop-filter: blur(10px);
  height: 600px;
  display: flex;
  flex-direction: column;
}

.todo-card .el-card__header {
  padding: 15px 20px;
  flex-shrink: 0;
}

.todo-card .el-card__body {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  padding: 0 20px;
}

.todo-card h2 {
  text-align: center;
  margin: 0 0 20px;
  color: #303133;
  font-size: 28px;
}

.input-with-select {
  width: 90%;
  margin: 0 auto 20px;
}

.input-with-select .el-input__inner {
  height: 45px;
  font-size: 16px;
}

.input-with-select .el-button {
  height: 45px;
  font-size: 16px;
}

.statistics-row {
  margin: 20px 0;
  text-align: center;
  flex-shrink: 0;
}

.completed-text {
  text-decoration: line-through;
  color: #909399;
}

.el-table .success-row {
  background: #f0f9eb;
}

/* 移除渐变背景，使用纯色 */
body {
  background-color: #f5f7fa;
}

/* 移除可爱风格的动画效果 */
.el-button.is-circle:hover {
  transform: none;
}

/* 恢复表情特效相关样式，移除 display: none */
.follow-emoji {
  position: fixed;
  pointer-events: none;
  z-index: 9999;
  animation: emojiPulse 1.5s ease-in-out forwards;
  text-shadow: 0 0 10px rgba(255, 255, 255, 0.8);
}

@keyframes emojiPulse {
  0% {
    transform: translate(-50%, -50%) scale(0.5);
    opacity: 0;
  }
  20% {
    transform: translate(-50%, -50%) scale(1.2);
    opacity: 0.8;
  }
  50% {
    transform: translate(-50%, -50%) scale(1);
    opacity: 1;
  }
  100% {
    transform: translate(-50%, -50%) scale(1.5);
    opacity: 0;
  }
}

.todo-item {
  padding: 20px 30px;
  font-size: 16px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
  transition: all 0.3s;
}

.todo-item:hover {
  background-color: rgba(245, 247, 250, 0.5);
}

.todo-item:last-child {
  border-bottom: none;
}

.todo-actions {
  text-align: right;
}

.action-buttons {
  display: inline-flex;
  gap: 8px;  /* 控制按钮之间的间距 */
}

.completed-text {
  text-decoration: line-through;
  color: #909399;
  transition: all 0.3s;
}

/* 移除按钮组的边框样式 */
.el-button-group {
  display: inline-flex;
  gap: 8px;
}

.el-button-group .el-button {
  margin-left: 0 !important;
  border-radius: 50% !important;
}

/* 确保圆形按钮样式正确 */
.el-button.is-circle {
  padding: 8px;
}

/* 优化按钮悬浮效果 */
.el-button.is-circle:hover {
  transform: none;
}

/* 优化按钮样式 */
.el-button {
  backdrop-filter: blur(5px);
}

.todo-list {
  flex: 1;
  overflow-y: auto;
  padding-right: 10px;
}

.todo-list::-webkit-scrollbar {
  width: 6px;
}

.todo-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.todo-list::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

.todo-list::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

.el-empty {
  margin: auto;
}

.el-statistic-number {
  font-size: 24px !important;
}

.todo-item .el-row .el-col-2 {
  width: 5%;
}

.todo-item .el-col-16 {
  width: 75%;
}

.todo-item .el-col-6 {
  width: 20%;
}
</style> 